package com.qianbao.finance.sync.common.aspect;


import com.qianbao.finance.sync.common.support.orm.db.SyncDynamicDataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * 切入BaseDao 根据 databaseName 获取对应的DataSource
 */
@Aspect
@Component
public class SyncDataSourceAspect {
    private static Logger LOG = LoggerFactory.getLogger(SyncDataSourceAspect.class);

    private static Map<String, String> mapper = new HashMap<String, String>() {{
            put("qbjfzh2db", "syncBizs1DataSource");
            put("qbjfzh1db", "syncBiz0DataSource");
            put("qbjfzhdb", "syncDataSource");
        }};


    @Pointcut("@annotation(com.qianbao.finance.sync.common.annotation.SyncDataSource)")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        Object[] obj = point.getArgs();
        String dataSource = null;
        String dataName = null;
        if (obj.length == 1) {
            dataName = String.valueOf(obj[0]);
        } else if (obj.length > 1) {
            dataName = String.valueOf(obj[obj.length - 2]);
        }
        dataSource = mapper.get(dataName);
        SyncDynamicDataSource.setDataSourceType(dataSource);
        LOG.debug("use datasource : {}", dataSource);
        try {
            return point.proceed();
        } finally {
            SyncDynamicDataSource.clearDataSourceType();
            LOG.debug("clear datasource...");
        }

    }

}
